﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using bdnt_pets_system_Entity;
using System.IO;
using bdnt_pets_system_Bo.DataManager;
using System.Collections.Generic;

namespace bdnt_pets_system.Web.Services
{
    [ServiceContract(Namespace = "")]
    //[SilverlightFaultBehavior]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UploadFileService
    {
        [OperationContract]
        public void DoWork()
        {
            // 在此处添加操作实现
            return;
        }

        FailureTrackingManager fManager = new FailureTrackingManager();
        [OperationContract]
        public bool UploadFile(Tbl_TrakingAttachment request)
        {
            //string uploadFolder = System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ConnectionString
            string fileExtName = System.Configuration.ConfigurationManager.AppSettings["imgExt"];

            string uploadFolder = System.Web.Hosting.HostingEnvironment.MapPath("~") + @"\UpLoad\Traking\";
            //string uploadFolder = System.Configuration.ConfigurationManager.AppSettings["AttachPath"];
            //string uploadFolder = @"E:\DCHY\bdnt-pets-system\bdnt-pets-system\bdnt-pets-system\bdnt-pets-system.Web\Upload\";
            //string savaPath = request.FilePath;
            //string dateString = DateTime.Now.ToShortDateString() + @"\";
            string fileName = request.FileName + request.ExtName;
            //Stream sourceStream = request.FileData;
            FileStream targetStream = null;
            try
            {
                if (request.FileData == null || request.FileData.Length == 0)
                {
                    return false;
                    //throw new Exception("数据流不可读!");
                }
                if (fileExtName.IndexOf(request.ExtName.ToLower()) >= 0)
                {
                    request.FileType = "1";
                }
                //if (savaPath == null) savaPath = @"Photo\";
                //if (!savaPath.EndsWith("\\")) savaPath += "\\";

                uploadFolder = !string.IsNullOrEmpty(request.FilePath) ? uploadFolder + request.FilePath + "\\" : uploadFolder;
                if (!Directory.Exists(uploadFolder))
                {
                    Directory.CreateDirectory(uploadFolder);
                }

                string filePath = Path.Combine(uploadFolder, fileName);
                request.FilePath = filePath;
                using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    //read from the input stream in 4K chunks
                    //and save to output stream

                    //int bufferLen = (int)request.FileData.Length;
                    //byte[] buffer = new byte[bufferLen];
                    //byte[] buffer = request.FileData;
                    //int count = 0;
                    //targetStream.Write(buffer, 0, count);
                    //while ((count = targetStream.Read(buffer, 0, buffer.Length)) > 0)
                    //{

                    //    targetStream.Write(buffer, 0, count);
                    //}
                    targetStream.Write(request.FileData, 0, request.FileData.Length);
                    //targetStream.Write(buffer, 0, buffer.Length);
                    //while ((count = buffer[count]) > 0)
                    //{

                    //    targetStream.Write(buffer, 0, count);
                    //}


                }
                fManager.SaveTrakingAttachment(request);
                return true;
            }
            catch (Exception)
            {
                return false;
                //throw;
            }
            finally
            {
                if (targetStream != null)
                    targetStream.Close();
                //if (sourceStream != null)
                //    sourceStream.Close();
            }
        }

        [OperationContract]
        public bool DeleteTrakingAttachment(Tbl_TrakingAttachment request)
        {
            if (string.IsNullOrEmpty(request.FilePath))
                return false;
            try
            {
                if (!File.Exists("@" + request.FilePath))
                {
                    File.Delete(request.FilePath);
                }
                return fManager.DeleteTrakingAttachment(request.Id);
            }
            catch (Exception)
            {
                return false;
            }
        }

        [OperationContract]
        public List<Tbl_TrakingAttachment> GetTrakingAttachmentByCondition(int trackingId,
         int pageSize, int currentPage)
        {
            var cuos = fManager.GetTrakingAttachmentByCondition(trackingId, pageSize, currentPage);
            //var cuo = cuos.FirstOrDefault(p => p.IsDefault);
            //if (cuo != null)
            //    cuo.FileData = GetDefaultImg(cuo);
            return cuos;
        }
        [OperationContract]
        public int GetTrakingAttachmentCountByCondition(int trackingId)
        {
            return fManager.GetTrakingAttachmentCountByCondition(trackingId);
        }
        [OperationContract]
        public bool SetDefaultImg(Tbl_TrakingAttachment cuObj)
        {
            return fManager.SetDefaultImg(cuObj);
        }

        [OperationContract]
        public byte[] GetDefaultImg(Tbl_TrakingAttachment cuObj)
        {
            FileStream stream = null;
            try
            {
                if (string.IsNullOrEmpty(cuObj.FilePath))
                {
                    return null;
                }
                
                if (!File.Exists(cuObj.FilePath))
                {
                    return null;
                }
                FileInfo cuFil = new FileInfo(cuObj.FilePath);
                if (cuFil == null)
                {
                    return null;
                }
                stream = cuFil.OpenRead();
                byte[] buffer = new byte[stream.Length + 1];

                //将文件读入字节数组
                stream.Read(buffer, 0, buffer.Length);
                return buffer;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (stream != null)
                    stream.Close();
            }
        }
    }
}
